﻿
using Commons;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace CamScanWorker
{
    class Program
    {
     static  MSMQListener _MSMQListener = new MSMQListener(ConfigurationManager.AppSettings["QueuePath"]);
        static void Main(string[] args)
        {
            _MSMQListener.MessageReceived += _MSMQListener_MessageReceived;
            try
            {
                _MSMQListener.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error staring the MSMQ Listener \n" + ex.Message);
                return;
            }
            while (Console.ReadKey().KeyChar != 'q')
            {
                
            }
            try
            {
                _MSMQListener.Stop();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error stopping the MSMQ Listener \n" + ex.Message);
            }
            Console.Read();
        }

        static void _MSMQListener_MessageReceived(object sender, MessageEventArgs args)
        {
            string path=((Result)args.MessageBody).Path;
            Console.WriteLine("recieve :" + path);
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = string.Format(@"/C {0} {1}  {2}{3} {4}{5} True", ConfigurationManager.AppSettings["PyexePath"], ConfigurationManager.AppSettings["PyscriptPath"], ConfigurationManager.AppSettings["InputPath"], path, ConfigurationManager.AppSettings["OutputPath"],path);
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            if (!process.HasExited)process.Kill();
            //try
            //{
            //    Console.WriteLine("sending back :" + path);
            //    Result result = new Result();
            //    //result.OCRText = "haha";
            //    result.Path = path;
            //    System.Messaging.Message msg1 = new System.Messaging.Message();
            //    msg1.Body = result;
            //    MessageQueue msgQ1 = new MessageQueue(ConfigurationManager.AppSettings["OutQueuePath"]);
            //    msgQ1.Send(msg1);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("Error creating the message \n" + ex.Message);
            //}
            Console.WriteLine("process end :" + path);
        }
    }
}
